import { Directive, ElementRef, Input } from '@angular/core';

@Directive({
  selector: '[appText]'
})
export class TextDirective {
  @Input() text: string;
  constructor(public el: ElementRef) {

  }
  ngOnInit(): void {
    //Called after the constructor, initializing input properties, and the first call to ngOnChanges.
    //Add 'implements OnInit' to the class.
    if(this.text){
      let len = this.getlen(this.text);
      let index  = this.getI(this.text);
      if(len>=88){
          if(index){
            let text  =  this.text.substr(0,index);
            this.el.nativeElement.innerHTML = text+'...';
          }
      }
    }
  }


  getlen(str): number {
    let len = 0;
    for (let i = 0; i < str.length; i++) {
      var a = str.charAt(i);
      if (a.match(/[^\x00-\xff]/ig) != null) {
        len += 2;
      }
      else {
        len += 1;
      }
    }
    return len;
  }

  getI(str){
    let len = 0,i;
    for (i = 0; i < str.length; i++) {
      if(len===87||len ===88 || len ===89){
        return i;
      }
      var a = str.charAt(i);
      if (a.match(/[^\x00-\xff]/ig) != null) {
        len += 2;
      }
      else {
        len += 1;
      }
    }
    return null;
  }
}
